<template>
  <section>
    <!--工具条-->
    <el-col :span="24" class="toolbar">
      <el-form :inline="true" :model="formInline" class="demo-form-inline" ref="form">
        <el-form-item>
          <Search :allOpts="formInline.allOpts" v-model="formInline.cOpts" @blur="getData"></Search>
        </el-form-item>
        <el-form-item>
          <el-button @click="handleAdd" :disabled="butStatus.add" type="success">创建</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="warning" @click="handleUpdate" :disabled="butStatus.update">修改</el-button>
        </el-form-item>
        <el-form-item>
          <el-button @click="handleDelete" :disabled="butStatus.rm" type="danger">删除</el-button>
        </el-form-item>
      </el-form>
    </el-col>

    <!--列表-->
    <el-table v-loading="listLoading" :data="tableData" border stripe style="width: 100%"
              @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column v-for="item in tableTile" :prop="item.key" :label="item.name"></el-table-column>
    </el-table>

    <el-col :span="24" class="toolbar" style="padding-bottom:10px;">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pageParm.currentPage"
        :page-sizes="[10, 20, 50]"
        :page-size="pageParm.page_size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pageParm.count" style="float:right">
      </el-pagination>
    </el-col>

    <!--编辑界面-->
    <el-dialog :title="formTitle" v-model="dialogFormVisible" size="tiny" @close="resetForm">
      <el-form :model="form" ref="form" :rules="editFormRules" :label-width="formLabelWidth">
        <el-form-item label="用户名" prop="user_name">
          <el-input v-model="form.user_name"
                    auto-complete="off"
                    :disabled="name_disabled"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input type="password" v-model="form.password" auto-complete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="再次输入密码" prop="checkPass">
          <el-input type="password" v-model="form.checkPass" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="绑定角色" prop="role_id" :label-width="formLabelWidth">
          <el-select v-model="form.role_id" placeholder="请选择" @change="roleEleCG" style="width: 100%;">
            <el-option
              v-for="item in roleOptions"
              :label="item.role_name"
              :value="item.role_id">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="系统级" prop="is_sys_user">
          <el-switch
                  v-model="form.is_sys_user"
                  on-text=""
                  off-text="">
          </el-switch>
        </el-form-item>


        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input v-model="form.phone" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="描述" prop="user_desc">
          <el-input v-model="form.user_desc" type="textarea"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="resetForm">取 消</el-button>
        <el-button type="primary" @click.native="editSubmit" :loading="editLoading">{{btnEditText}}</el-button>
      </div>
    </el-dialog>

  </section>
</template>

<script>
  import util from '../../common/util'
  import Search from '../../components/Search.vue'
  import dao from '../../common/dao'
  import NProgress from 'nprogress'
  import { mapGetters } from 'vuex'

  export default {
    components: {Search},
    computed: {
      ...mapGetters([
        'getUser'
      ])
    },
    data () {
      return {
        btnEditText: '保存',
        formTitle: '创建用户权限',
        formLabelWidth: '120px',
        roleOptions: [
          {
            role_id: '1',
            role_name: '12',
          }, {
            role_id: '2',
            role_name: '3123',
          }
        ],
        abcd: '',
        form: {
          user_id: '',
          user_name: '',
          password: '',
          checkPass: '',
          role_id: '',
          role_name: '',
          email: '',
          phone: '',
          user_desc: '',
          is_sys_user:false
        },
        butStatus: {
          update: true,
          add: false,
          rm: true,
        },
        formInline: {
          allOpts: [{
            key: 'user_name',
            label: '用户',
            type: '',
            val: ''
          },
            {
              key: 'role_name',
              label: '角色',
              type: '',
              val: ''
            }],
          cOpts: [{
            key: 'user_name',
            label: '用户',
            type: '',
            val: ''
          },
            {
              key: 'role_name',
              label: '角色',
              type: '',
              val: ''
            }]
        },
        dialogFormVisible: false,
        editFormRules: {
          user_name: [
            {required: true, message: '请输入用户名！', trigger: 'blur'},
            {validator: util.validateString, trigger: 'blur'}
          ],
          password: [
            {required: true, validator: this.validatePass, trigger: 'blur'},
            {validator: util.validatePWS, trigger: 'blur'}
          ],
          checkPass: [
            {required: true, validator: this.validatePass2, trigger: 'blur'}
          ],
          role_id: [
            {required: true, message: '请选择角色', trigger: 'change'},
          ],
          email: [
            {type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur,change'}
          ],
          phone: [
            {alidator: util.validateTel, trigger: 'blur'}
          ]
        },
        tableTile: [{
          key: 'user_name',
          name: '用户名称',
        }, {
          key: 'role_names',
          name: '已绑定角色',
        }, {
          key: 'last_logintime',
          name: '上次登录时间',
        }, {
          key: 'operator_user_name',
          name: '创建者',
        }],
        tableData: [],
        tipsClass: "",
        pageParm: {
          "count": 0,//总条数
          "page_size": 20,//每页条数
          "page_count": 0,//总页数
          "currentPage": 1//当前页数
        },
        name_disabled: false
      }
    },
    methods: {
      roleEleCG(item){
      },
      validatePass (rule, value, callback) {
        if (value === '') {
          callback(new Error('请输入密码'));
        } else {
          if (this.form.checkPass !== '') {
            this.$refs.form.validateField('checkPass');
          }
          callback();
        }
      },
      validatePass2 (rule, value, callback) {
        if (value === '') {
          callback(new Error('请再次输入密码'));
        } else if (value !== this.form.password) {
          callback(new Error('两次输入密码不一致!'));
        } else {
          callback();
        }
      },
      handleAdd () {
        this.dialogFormVisible = true;
        this.name_disabled = false;
        this.formTitle = '创建用户权限'
        //清空数据
        this.form = {
          user_id: "",
          user_name: "",
          password: "",
          checkPass: "",
          role_id: "",
          email: "",
          phone: "",
          user_desc: "",
          is_sys_user:false
        };

        this.name_disabled = false;
      },
      handleUpdate () {

        this.dialogFormVisible = true;
        this.formTitle = '修改用户权限'
        let selectedRow = this.multipleSelection[0];
        this.tableData.map(rowData => {
          if (rowData.user_id === selectedRow.user_id) {
            let role_id = "";
            if (rowData.roles && rowData.roles.length > 0) {
              role_id = rowData.roles[0].role_id;
            }
            this.form = {
              user_id: rowData.user_id,
              user_name: rowData.user_name,
              password: rowData.password,
              checkPass: rowData.checkPass,
              role_id: role_id,
              email: rowData.email,
              phone: rowData.phone,
              user_desc: rowData.user_desc,
              is_sys_user: rowData.is_sys_user==0
            };
            this.name_disabled = true;
          }
        });
      },
      handleDelete () {
        let user_ids = [];
        let isCurrentUser = false;
        let user_id = this.getUser.user_id || ""; //获取user_id
        this.multipleSelection.map(rowData => {
          if (rowData.user_id == user_id) {
            isCurrentUser = true;
          }
          user_ids.push(rowData.user_id);
        });
        if (user_ids.length === 0) {
          this.$message({
            message: '请至少选择一条记录！',
            type: 'warning'
          });
        } else if (isCurrentUser) {
          this.$message({
            message: '不能删除当前登录的用户！',
            type: 'warning'
          });
        } else {
          this.$confirm('确认删除吗？', '提示', {
            type: 'info'
          }).then(() => {

            let cd = true; //是否可以执行删除

            user_ids.map(h => {
              this.tableData.map(i => {
                if (h == i.user_id) {
                  if (i.task_count > 0) {
                    this.$message({
                      message: `${i.user_name} 绑定角色任务在运行，不能删除！`,
                      type: 'warning'
                    })
                    cd = false;
                    return false
                  }
                }
              })
            })

            if (cd) {
              dao.deleteUser(user_ids).then((response) => {
                if (!response.body || response.body.retCode != 200) {
                  util.apiMsg(response);
                  return false;
                } else {
                  this.$message({
                    type: 'success',
                    message: '删除成功!'
                  });
                  //刷新列表
                  this.getData();
                }
              })
            }

          });
        }
      },
      editSubmit () {

        this.$refs.form.validate((valid) => {
          if (valid) {
            this.$confirm('确认提交吗？', '提示', {
              type: 'info'
            }).then(() => {
              for (let o of this.roleOptions) {
                if (o.role_id == this.form.role_id) {
                  this.form.role_name = o.role_name
                  break;
                }
              }
              //处理参数
              let role = [{
                role_id: this.form.role_id,
                role_name: this.form.role_name,
                operator_user_id: ''
              }];
              this.form.roles = role;
              this.btnEditText = '提交中';
              this.editLoading = true;
              let fun ,form = JSON.parse(JSON.stringify(this.form));
              form.is_sys_user = this.form.is_sys_user?0:1;
              form.password = util.rsaEncryption(form.password)
              form.checkPass = util.rsaEncryption(form.checkPass)
              if (this.form.user_id == '') {
                //create
                fun = dao.addUser(form)
              } else {
                //update
                fun = dao.updateUser(form)
              }
              fun.then((response) => {
                this.btnEditText = '提 交';
                this.editLoading = false;
                this.dialogFormVisible = false;
                if (!response.body || response.body.retCode != 200) { return false; }
                else {
                  this.$message({
                    type: 'success',
                    message: '提交成功!'
                  });
                  //刷新列表
                  this.getData();
                }
              });
            })
          } else {
            return false;
          }
        })
      },
      getRole () {

        dao.getRoleGet({
          "role_name": "",
          "start_index": 1,
          "page_count": 99999
        }).then(response => {
          if (!response.body || response.body.retCode != 200) {
            util.apiMsg(response);
            return false;
          }
          let pageRes = response.body;
          let roleOptions = [];
          if (pageRes.results != null) {
            pageRes.results.map(roleOption => {
              roleOptions.push({
                role_id: roleOption.role_id + "",
                role_name: roleOption.role_name
              });
            });
          }
          roleOptions.sort(function (a, b) {
            return (a.role_id - b.role_id);
          });
          this.roleOptions = roleOptions;
        })
      },
      getData () {
        let body = {}
        this.formInline.cOpts.map(item => {
          body[item.key] = item.val
        })
        body.start_index = this.pageParm.currentPage;
        body.page_count = this.pageParm.page_size
        dao.getUser(body).then(response => {
          if (!response.body || response.body.retCode != 200) {
            util.apiMsg(response);
            return false;
          }
          let pageRes = response.body;
          this.tableData = pageRes.results;
          if (this.tableData != null) {
            this.tableData.map(rowData => {
              if (rowData.roles != null && rowData.roles.length > 0) {
                //修改为一个用户绑定一个角色
                if (rowData.roles != null) {
                  rowData.role_id = rowData.roles[0].role_id;
                  rowData.role_names = rowData.roles[0].role_name
                }
              }
            });
          }
          this.pageParm.count = parseInt(pageRes.count);
        });
      },
      updateButStatus (val) {
        if (val.length == 1) {
          this.butStatus.update = false;
          this.butStatus.rm = false;
        } else if (val.length == 0) {
          this.butStatus.update = true;
          this.butStatus.rm = true;
        } else {
          this.butStatus.update = true;
          this.butStatus.rm = false;
        }
      },
      handleSelectionChange (val) {
        this.multipleSelection = val
        this.updateButStatus(val)
      },
      handleSizeChange (val) {
        this.pageParm.page_size = val;
        this.getData();
      },
      handleCurrentChange (val) {
        this.pageParm.currentPage = val;
        this.getData();
      },
      validateUserName (rule, value, callback) {
        if (this.name_disabled) {
          callback()
          return false
        }
        if (!value) {
          callback(new Error('请输入用户名！'))
        } else {
          dao.getValidateUser({
            "user_name": this.form.user_name,
            "user_id": this.form.user_id
          }).then((response) => {
            if (!response.body || response.body.retCode != 200) {
              return false
            }
            if (!response.body.result) {
              callback()
            } else {
              callback(new Error('用户名重复！'))
            }
          })
        }
      },
      resetForm () { //重置表单
        this.$refs.form.resetFields();
        this.dialogFormVisible = false;
      }
    },
    mounted () {
      this.getData();
      this.getRole();
    }
  }
</script>

<style scoped>
  .toolbar .el-form-item {
    margin-bottom: 10px;
  }

  .toolbar {
    background: #fff;
    padding: 10px 10px 0px 10px;
  }
</style>